<template>
  <div class="login-container">
    <el-card>
      <h1>员工登录</h1>
      <el-form>
        <el-form-item label="账号" prop="username" clearable>
          <el-input v-model="account" class="input-box" style="width: 240px" placeholder="请输入账号" clearable />
        </el-form-item>
        <el-form-item class="" label="密码" prop="password">
          <el-input v-model="password" style="width: 240px" type="password" placeholder="请输入密码" show-password />
        </el-form-item>
        <el-form-item class="button-container">
          <div style="justify-content: space-between;">
          <el-button style="margin-left: 70px;" type="primary" @click="login">登录</el-button>
          <el-button  type="primary" @click="exit">返回</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
import axios from '@/utils/request';
import { empAccount } from '@/store';
import moment from 'moment';
import { removeToken, setToken } from '@/utils/auth';
let empStore = empAccount() 
const account = ref('')
const password = ref('')
const router = useRouter();
 const login = async () => {
  try {
    // 发送POST请求到服务器，尝试使用提供的账号和密码进行登录
    const result = await axios.post('/emp/login', {
      account: account.value,
      password: password.value
    });
    // 检查服务器返回的状态码
    if (result.data.code === 1) {
      // 登录成功，显示成功消息
      ElMessage.success('登录成功');
      //移除token
      removeToken()
      //设置token
      setToken(result.data.data)
      //添加账号
      empStore.$state.account = account.value
      // 导航到用户主页
      router.push('/userHome');
    } else {
      // 登录失败，显示错误消息
      ElMessage.error(result.data.data);
    }
  } catch (error) {
    // 捕获并处理请求过程中可能发生的错误
    console.error('登录时发生错误:', error);
    // 显示通用错误消息
    ElMessage.error('登录时发生错误，请检查网络或联系管理员');
  }
};

//返回主页
const exit = () => {
  router.push('/')
}
</script>

<style scoped>
.login-container {
  padding: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: beige;
  height: 100vh;
}

/* .el-form-item.button-container {
  position: relative;
}

.el-button {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
} */
</style>
